package com.tim.app.ui.activity.some_homepage;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.Story;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.StoryListResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.record.RecordActivity;
import com.tim.app.ui.activity.StoryDetailActivity;
import com.tim.app.ui.adapter.someone_homepage.HomepageStoryAdapter;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * 某人的故事页面
 */
public class SomeoneStoryActivity extends BaseActivity implements LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "SomeoneStoryActivity";

    private ImageButton ibBack;
    private ImageButton ibCreateRecord;
    private TextView tvTitle;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvStory;

    private HomepageStoryAdapter adapter;
    private List<Story> dataList;
    private EmptyLayout emptyLayout;

    private User currentUser;

    public static void start(Context context, User user) {
        Intent intent = new Intent(context, SomeoneStoryActivity.class);
        intent.putExtra(AppKey.USER, user);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_someone_story;
    }


    @Override
    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ibBack = (ImageButton) findViewById(R.id.ibBack);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        ibCreateRecord = (ImageButton) findViewById(R.id.ibCreateRecord);

        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvStory = (WrapRecyclerView) findViewById(R.id.wrvStory);
        wrvStory.setOverScrollMode(View.OVER_SCROLL_NEVER);

        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);

        emptyLayout = new EmptyLayout(this, load_more);
        emptyLayout.showLoading();
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_story);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvStory.setLayoutManager(layoutManager);

        wrvStory.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.dimen_5)).build());

        dataList = new ArrayList<>();
        adapter = new HomepageStoryAdapter(this, dataList);
        wrvStory.setAdapter(adapter);

        adapter.setOnItemClickListener(this);
        ibBack.setOnClickListener(this);
        ibCreateRecord.setOnClickListener(this);

        currentUser = (User) getIntent().getSerializableExtra(AppKey.USER);

        if (null != currentUser) {
            if (UserManager.ins().getUserId().equals(currentUser.getUserId())) {
                tvTitle.setText(getString(R.string.myStory));
                emptyLayout.setEmptyText("你还没有发布过故事", "");
                ibCreateRecord.setVisibility(View.VISIBLE);
            } else {
                ibCreateRecord.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(currentUser.getName())) {
                    tvTitle.setText(getString(R.string.someoneStory, currentUser.getName()));
                }
                if (currentUser.getSex() == 1) {
                    emptyLayout.setEmptyText("他还没有发布过故事", "");
                } else {
                    emptyLayout.setEmptyText("她还没有发布过故事", "");
                }
            }
        }
        EventManager.ins().registListener(EventTag.ON_STORY_DELETED, eventListener);
    }

    int pageNum = 1;//页码

    @Override
    public void initData() {
        pageNum = 1;
        API_Found.ins().getSomeonStoryList(TAG, currentUser.getUserId(), pageNum, AppKey.PAGE_SIZE, refreshCallback);
    }


    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                StoryListResult result = new Gson().fromJson(resultValue, StoryListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum == result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, false);
                    } else {
                        load_more.loadMoreFinish(false, true);
                    }
                }

                if (dataList == null || dataList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                StoryListResult result = new Gson().fromJson(resultValue, StoryListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum == result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, false);
                    } else {
                        load_more.loadMoreFinish(false, true);
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.ON_STORY_DELETED, eventListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getSomeonStoryList(TAG, currentUser.getUserId(), pageNum + 1, AppKey.PAGE_SIZE, moreCallback);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack://返回
                finish();
                break;
            case R.id.ibCreateRecord://发表故事
                RecordActivity.start(this, "");
                break;
        }
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_STORY_DELETED:
                    String deleteId = (String) dataobj;
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i).getId().equals(deleteId)) {
                            dataList.remove(i);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public void onItemClick(View view, int position, long id) {
        ArrayList<Story> list = new ArrayList<>();
        list.add(dataList.get(position));
        StoryDetailActivity.start(this, list, 0, false);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

}
